﻿
// reference local blank image
Ext.BLANK_IMAGE_URL = '../resources/images/default/s.gif';
 
 function handleInfo(data) {
    var response = eval(data.currentTarget.responseText);
  
    alert('Target: ' + response.Target + "\n" + 
          'Scope: ' + response.Scope + "\n" +
          'Secure: ' + response.Secure);
}

 
 
// create namespace
Ext.namespace('BloggerImport');

BloggerImport = {

    blogEntryStore: null,

	authorMapStore: null,
	
	authorMapWin: null,
    
    blogList: null,
    
    service: null,

	featuresPostedCount: null,

    scope: "http://www.blogger.com/feeds",

    init: function(){
    
        BloggerImport.checkBloggerLogin();
    },
    
    checkBloggerLogin: function(){

        var token = google.accounts.user.checkLogin(BloggerImport.scope);
        if(!token)
        {
            Ext.MessageBox.alert("Login","You are not logged into the Blogger service. " +
				"You will be redirected to Google to authorize the Blogger Import application.",function(btn){
                if(btn == "ok")
                {
                    google.accounts.user.login(BloggerImport.scope);
                }
            }); //end login alert msgbox
        }
        else
        {
            BloggerImport.blogList = new Ext.data.SimpleStore({
                fields: ['url','title'],
                data: [[],[]]
            });

            BloggerImport.blogEntryStore = new Ext.data.Store({
                url: "proxy.php?url=",
                reader: new Ext.data.XmlReader({
                    record: 'entry',
                    id: 'id'
                },
                [
                    "title", {name: 'author', mapping: 'author > name'},  'summary', 'content', 'updated', {name: 'category', convert: function(v,rec){
							//alert("converting " + v);
							var elements = Ext.query('category',rec);
							var outString = "";
    						for (var i = 0, element; element = elements[i]; i++) {
								outString += element.attributes[0].value + (i < elements.length - 1 ? "|" : "")
							}
							return outString;
	
							} 
						} //end of category column
                ])
            });

            BloggerImport.blogEntryStore.on('load', function(store, recs, opts){
                BloggerImport.changeStatus(recs.length + " records loaded.");
				Ext.getCmp('authorMappingButton').enable();
				Ext.getCmp('importAllButton').enable();
            });

            BloggerImport.blogEntryStore.on('loadexception', function(proxy, opts, response, e){
                alert(e);
            });
           
            var viewport = new Ext.Viewport({
                layout: 'border',
                items: [{
                    xtype: 'grid',
                    title: "Blogger Import Tool",
                    region: 'center',
					store: BloggerImport.blogEntryStore,
                    tbar: [
                        { text: 'Load Feed', id: 'loadFeedButton', handler: BloggerImport.LoadATOM, icon: 'resources/images/default/tree/folder-open.gif', cls: "x-btn-text-icon" },
                        { xtype: 'tbseparator' },
                        { xtype: 'tbtext', text: 'Destination:'},
                        { xtype: 'combo', id: 'destBlogCombo', displayField: 'title', valueField: 'url', mode: 'local', store: BloggerImport.blogList, triggerAction: 'all', forceSelection: true },
						{ text: 'Author Mapping', handler: BloggerImport.ShowAuthorMap, disabled: true, id: 'authorMappingButton' },
						{ text: 'Import All', handler: BloggerImport.ImportAll, disabled: true, id: 'importAllButton' },
                        { xtype: 'tbfill' },
                        { text: 'Logout', handler: BloggerImport.Logout }
                    ],
                    bbar: new Ext.StatusBar({
                        defaultText: 'Blogger Import 0.1',
                        id: 'statusbar',
                    }),
					columns: [
						{header: "Title", dataIndex: 'title'},
						{header: "Author", dataIndex: 'author'},
						{header: "Updated", dataIndex: 'updated'},
						{header: "Categories", dataIndex: 'category'},
						{header: "Content", dataIndex: 'content', id: 'content'}
					],
					autoExpandColumn: 'content'
                }]
            });
            
            BloggerImport.service = new google.gdata.blogger.BloggerService('BloggerImport');
 
            //load list of blogs
            var query = new google.gdata.blogger.BlogQuery('http://www.blogger.com/feeds/default/blogs');
            BloggerImport.service.getBlogFeed(query, BloggerImport.HandleBlogList, BloggerImport.handleError);

        }

    },
    
    LoadATOM: function(){
        //load atom file
        //alert("Loading ATOM");
        Ext.MessageBox.prompt("Import Data URL","Please enter the URL of the ATOM feed you wish to import:",function(btn,feedURL){
        
            if(btn == 'ok')
            {
                //need to clean up everything else here too... load a new feed, reset mapping and other stuff
				BloggerImport.blogEntryStore.removeAll();
                BloggerImport.blogEntryStore.proxy.conn.url = "proxy.php?url=" + feedURL;
               
                BloggerImport.blogEntryStore.load();
            }
        
        });
    },

	ImportAll: function(){
		if(BloggerImport.blogEntryStore.getCount())
		{
			BloggerImport.featuresPostedCount = 0;
			BloggerImport.blogEntryStore.each(BloggerImport.processRecord,BloggerImport);
			BloggerImport.changeStatus(BloggerImport.featuresPostedCount + (BloggerImport.featuresPostedCount == 1 ? " post" : " posts") + " successfully imported to blog.");
			
		}
		//foreach row
			//unpack categories
			//replace author
			//compose json
			//post
			//check status - flag or count somehow
		//report results
	},
	
	processRecord: function(rec){
		//unpack categories
		var categoriesArray = BloggerImport.unpackCategories(rec.get("category"));
		var categoriesObj = new Array();
		for (category in categoriesArray)
		{
			categoriesObj.push({term: categoriesArray[category], scheme: 'http://www.blogger.com/atom/ns#'});
		}
		//replace author
		var authorsObj = BloggerImport.mapAuthors(rec.get("author"));
		//compose json
		var timestring = rec.get("updated");
		if(timestring.charAt(19) == '-')
		{ //fix for google's fromIso8601 function
			timestring = timestring.substring(0,19) + ".000" + timestring.substring(19);
		}
		var published = google.gdata.DateTime.fromIso8601(timestring);
		
		var newEntry = new google.gdata.blogger.BlogPostEntry({
			authors: authorsObj,
			title: {type:'html', text: rec.get("title")},
			content: {type: 'html', text: rec.get("content")},
			published: {value: published},
			categories: categoriesObj
		});
		//post
		BloggerImport.service.insertEntry(Ext.getCmp('destBlogCombo').getValue(), newEntry, BloggerImport.postAddSuccess, BloggerImport.handleError);
		//check status - flag or count somehow
	},
	
	postAddSuccess: function(entryRoot){
		BloggerImport.changeStatus("Added a post.");
		BloggerImport.featuresPostedCount++;
	},
	
	unpackCategories: function(categoryString){
		return categoryString.split('|');
	},
	
	mapAuthors: function(authorName){
		if(BloggerImport.authorMapStore)
		{
			var mapRecIndex = BloggerImport.authorMapStore.find('sourceName', authorName);
			if(mapRecIndex != -1)
			{
				var mapRec = BloggerImport.authorMapStore.getAt(mapRecIndex);
				var name = (mapRec.get('name') != "" ? mapRec.get('name') : authorName);
				var email = (mapRec.get('email') != "" ? mapRec.get('email') : 'noentry@blogger.com');
				
				return [{name: name, email: email}];
			}
		}
		else
		{
			return [{name: authorName, email: 'noentry@blogger.com'}];
		}
	},
	
	ShowAuthorMap: function(){
		if(!BloggerImport.authorMapStore)
		{
			var names = BloggerImport.blogEntryStore.collect('author');
			for(var i = 0, name; name = names[i]; i++)
			{
				names[i] = [name,name,""]
			}
			if(names.length)
			{
				BloggerImport.authorMapStore = new Ext.data.SimpleStore({
                	fields: ['sourceName','name', 'email'],
                	data: names
				
				});
			}
		}
		if(!BloggerImport.authorMapWin)
		{
			BloggerImport.authorMapWin = new Ext.Window({
				layout:'fit',
				width:500,
				height:300,
				closeAction:'hide',
				title: 'Author Mapping Window',
				items: [{
					xtype: 'editorgrid',
					store: BloggerImport.authorMapStore,
					columns: [
						{header: 'Source Name', dataIndex: 'sourceName'},
						{header: 'Destination Name', dataIndex: 'name', editor: new Ext.form.TextField({})},
						{header: 'Destination Email', dataIndex: 'email', editor: new Ext.form.TextField({})}
					],
					clicksToEdit: 1,
					viewConfig: {forceFit: true, autoFill: true}
				}]
			});
		}
		BloggerImport.authorMapWin.show();

	},
    
    Logout: function(){
        google.accounts.user.logout();
    },
    
    HandleBlogList: function(listOfBlogs){
        //populate BloggerImport.blogList from listOfBlogs
        var blogEntries = listOfBlogs.feed.getEntries();
        if(!blogEntries.length) {
            return;
        }
        
        var blogsArray = [];
        
        for (var i = 0, blogEntry; blogEntry = blogEntries[i]; i++) {
            blogsArray[i] = [blogEntry.getEntryPostLink().getHref(), blogEntry.getTitle().getText()];
        }
        
        BloggerImport.blogList.on('load',function(store,recs,opts){
            if(store.getCount() > 0)
            {
                Ext.getCmp('destBlogCombo').setValue(recs[0].get('url'));
            }
			else
			{
				Ext.getCmp('loadFeedButton').disable();
			}
        });
        BloggerImport.blogList.loadData(blogsArray);
        //BloggerImport.blogList.fireEvent('load',BloggerImport.blogList)
        //BloggerImport.blogList.reload();

        BloggerImport.changeStatus(blogEntries.length + (blogEntries.length == 1 ? " blog" : " blogs") + " added to destinations list.")        

    },
    
    handleError: function(error){
        BloggerImport.changeStatus(error.cause ? error.cause.statusText : error.message);
    },
    
    changeStatus: function(statusText){
        var statusBar = Ext.getCmp('statusbar');
        statusBar.setStatus({text: statusText, clear: true});
    }

}